package com.ck.company.controller;

import com.ck.company.service.CpDeviceInfoService;
import com.ck.constant.ClientConstant;
import com.ck.constant.PageConstant;
import com.ck.core.BaseController;
import com.ck.exception.ControllerException;
import com.ck.model.common.User;
import com.ck.model.company.vo.CpDeviceDetailVO;
import com.ck.model.company.vo.CpDeviceInfoListVO;
import com.ck.util.HttpUtils;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * <p>Title: CpDeviceInfoController</p>  
 * <p>Description: 商家终端 ctrl</p>  
 * @author huangf 
 * @date 2018年6月21日
 */
@Controller
@RequestMapping(value = "/cpDeviceInfo")
public class CpDeviceInfoController extends BaseController{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired 
	private CpDeviceInfoService cpDeviceInfoService;
	/**
	 *  
	 * @param groupId 分组code
	 * @param deviceCode 序列号
	 * @param deviceIp  设备ip
	 * @param deviceMac mac地址
	 * @param deviceName 终端名（备注）
	 * @param deviceStatus 设备状态
	 * @param pageNum 分页-页数
	 * @param pageSize 分页-每页条数
	 * @param model
	 * @return
	 */
    @RequestMapping(value = "/listByPage")
    public Object listByPage( HttpServletRequest request,Long groupId, String deviceCode, String deviceIp, String deviceMac,String deviceName, Integer deviceStatus, Integer pageNum, Integer pageSize, Model model) {
		// 设置分页默认值
		if ( pageNum == null || pageSize == null ) {
			pageNum = PageConstant.DEFAULT_PAGE_NUM;
			pageSize = PageConstant.DEFAULT_PAGE_SIZE;
		}
		
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		Page<CpDeviceInfoListVO> page = cpDeviceInfoService.listByPage(user.getCompanyCode(),groupId, deviceCode, deviceIp, deviceMac, deviceName,deviceStatus, pageNum, pageSize);

		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("result", page.getResult());
		model.addAttribute("total", page.getTotal());
		model.addAttribute("resultList", page.getResult());
		//查询条件回显
		// 分组编号
		model.addAttribute("groupId",groupId);
		// 终端唯一编码
		model.addAttribute("deviceCode",deviceCode);
		// 终端mac
		model.addAttribute("deviceMac",deviceMac);
		// 终端名
		model.addAttribute("deviceName",deviceName);
		// 终端状态
		model.addAttribute("deviceStatus",deviceStatus);
		return new ModelAndView("cp/cp_deviceInfo_list");
	}
    
    /**
     * 更新终端详情部分信息
     * @param request
     * @param deviceCode 终端code地址
     * @return
     */
    @RequestMapping(value="/detail/update/{deviceCode}")
    @ResponseBody
    public Object updateDeviceDetail( HttpServletRequest request,@PathVariable String deviceCode,String province,String city,
    		String area,String detailAddr,String deviceName,Model model) {
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		try {
			cpDeviceInfoService.updateDeviceBasicInfo(deviceCode,deviceName, user.getCompanyCode(), province, city, area, detailAddr);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpDeviceInfoController updateDeviceDetail 终端详情更新失败：" + e.getMessage(),e);
			return new ControllerException("终端信息更新失败");
		}
    	return "";
    }
    
    /**
     * 终端详情页面
     * @param request
     * @param deviceCode 终端code
     * @return
     */
    @RequestMapping(value = "/detail")
    public Object deviceDetail( HttpServletRequest request,String deviceCode,Model model) {
    	User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
    	CpDeviceDetailVO deviceInfo = cpDeviceInfoService.getDeviceDetailByDeviceMacOrDeviceCode(user.getCompanyCode(), null, deviceCode);
    	model.addAttribute("device", deviceInfo);
    	return new ModelAndView("cp/cp_deviceInfo_detail");
    }
    
    /**
	 *  远程关机指令
	 */
	@ResponseBody
	@RequestMapping(value = "/shutdown")
	public Object shutdown(String deviceCodes, String groupIds, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		//	deviceCodes和groupCode不能同时为空
		if (StringUtils.isBlank(deviceCodes) && StringUtils.isBlank(groupIds)) {
			return new ControllerException(ClientConstant.MSG_PARAM_ERROR);
		}
		try {
			cpDeviceInfoService.shutdown(deviceCodes, groupIds, user, HttpUtils.getRemortIP(request) );
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpDeviceInfoController shutdown 关机失败：" + e.getMessage(),e);
			return new ControllerException("关机失败");
		}
		return "";
	}

	/**
	 * 重启
	 */
	@ResponseBody
	@RequestMapping(value = "/restart")
	public Object restart(String deviceCodes, String groupIds, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		//	deviceCodes和groupCode不能同时为空
		if (StringUtils.isBlank(deviceCodes) && StringUtils.isBlank(groupIds)) {
			return new ControllerException(ClientConstant.MSG_PARAM_ERROR);
		}
		try {
			cpDeviceInfoService.restart(deviceCodes, groupIds, user, HttpUtils.getRemortIP(request));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpDeviceInfoController restart 重启失败：" + e.getMessage(),e);
			return new ControllerException("重启失败");
		}
		return "";
	}

	/**
	 * 设置定时开关机
	 */
	@ResponseBody
	@RequestMapping(value = "/setTimerShutDownOrStart")
	public Object setTimerShutDownOrStart(String deviceCodes, String groupIds, String bootTime, String offTime, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if ((StringUtils.isBlank(deviceCodes) && StringUtils.isBlank(groupIds)) || StringUtils.isBlank(bootTime) || StringUtils.isBlank(offTime)) {
			return new ControllerException("输入参数不能为空");
		}
		try {
			cpDeviceInfoService.setBootAndOffTimmer(deviceCodes, groupIds, user, HttpUtils.getRemortIP(request), bootTime, offTime);;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpDeviceInfoController setTimerShutDownOrStart 设置定时开关机失败：" + e.getMessage(),e);
			return new ControllerException("设置定时开关机失败");
		}
		return "";
	}
	
	/**
	 * 设置定时开关屏
	 * @param deviceCodes
	 * @param groupIds
	 * @param bootTime
	 * @param offTime
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/setScreeenTimerShutDownOrStart")
	public Object setScreeenTimerShutDownOrStart(String deviceCodes, String groupIds, String bootTime, String offTime, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if ((StringUtils.isBlank(deviceCodes) && StringUtils.isBlank(groupIds)) || StringUtils.isBlank(bootTime) || StringUtils.isBlank(offTime)) {
			return new ControllerException("输入参数不能为空");
		}
		try {
			cpDeviceInfoService.setScreenOnAndOffTimmer(deviceCodes, groupIds, user, HttpUtils.getRemortIP(request), bootTime, offTime);;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpDeviceInfoController setScreeenTimerShutDownOrStart 设置定时开关屏失败：" + e.getMessage(),e);
			return new ControllerException("设置定时开关屏失败");
		}
		return "";
	}
	
	/**
	 * 设置音量
	 */
	@ResponseBody
	@RequestMapping(value = "/setVolume")
	public Object setVolume(String deviceCodes, String groupIds, Integer deviceVolume, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if ((StringUtils.isBlank(deviceCodes) && StringUtils.isBlank(groupIds)) || deviceVolume == null) {
			return new ControllerException("输入参数不能为空");
		}
		try {
			cpDeviceInfoService.setVolume(deviceCodes, groupIds, user, HttpUtils.getRemortIP(request), deviceVolume);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpDeviceInfoController setVolume 设置音量失败：" + e.getMessage(),e);
			return new ControllerException("设置音量失败");
		}
		return "";
	}

	/**
	 * 解绑终端
	 */
	@ResponseBody
	@RequestMapping(value = "/untie")
	public Object untie(String deviceCodes, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if (StringUtils.isBlank(deviceCodes)) {
			return new ControllerException("输入参数不能为空");
		}
		try {
			String ip = HttpUtils.getRemortIP(request);
			cpDeviceInfoService.untie(user.getCompanyCode(), deviceCodes, user, ip);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpDeviceInfoController untie 解绑终端失败：" + e.getMessage(),e);
			return new ControllerException("解绑终端失败");
		}
		return "";
	}

}
